// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// F [author] rhyme_lph
// V [email]  rhymelph@gmail.com
// P [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/http_service/http_category_service.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:flutter/material.dart';

class SelectTransactionPurposeProvider
    extends BaseProvider<List<SettingDataCategory>> with SearchDataListMixin {
  SettingDataCategory currentSelect;

  List<int> recentIds;

  bool isCashOut;

  @override
  Future get dataFuture => isCashOut == true
      ? HttpCategoryService.cashOutCategories()
      : HttpCategoryService.cashInCategories();

  @override
  void searchRefreshData(searchData) {}

  void onChangeSelect(SettingDataCategory item) {
    currentSelect = item;
    updateRecentUsedIds(item.id);
    if (currentSelect != item) {
      update();
    }
    obtainContext?.call((context) {
      Navigator.of(context).pop(currentSelect);
    });
  }

  @override
  FutureOr<List<SettingDataCategory>> transformData(
      List<SettingDataCategory> d, bool isCache) async {
    print('isCashOut $isCashOut');
    if (isCashOut == true) {
      RProvider.myProvider.globalMap[ConfigKey.cashOutCategory] = d;
      recentIds = Config.cashOutRecentIds;
      await RProvider.myProvider.updateGlobalMap();
    } else {
      RProvider.myProvider.globalMap[ConfigKey.cashInCategory] = d;
      recentIds = Config.cashInRecentIds;
      await RProvider.myProvider.updateGlobalMap();
    }
    return super.transformData(d, isCache);
  }

  void updateRecentUsedIds(int id) async {
    if (recentIds == null) {
      recentIds = [id];
    } else {
      recentIds.remove(id);
      recentIds.insert(0, id);
      if (recentIds.length > 5) {
        recentIds.removeLast();
      }
    }
    if (isCashOut) {
      RProvider.myProvider.globalMap[ConfigKey.cashOutRecentIds] = recentIds;
    } else {
      RProvider.myProvider.globalMap[ConfigKey.cashInRecentIds] = recentIds;
    }
    await RProvider.myProvider.updateGlobalMap();
  }
}
